﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ZLCMS.Data.Model;
using ZLCMS.Business.Util;
using NHibernate;
using DotNet.Common.NHibernateUtil;
using NHibernate.Criterion;
using ZLCMS.Commands.User.Commands.Product;
using DotNet.Common.Command;
using ZLCMS.Business.DwzFrame;
using ZLCMS.Commands.User.Util;

namespace ZLCMS.Web.SystemManage.Basics.Shop.Product
{
    public partial class ProductDetail : System.Web.UI.Page
    {
        private List<ShopCategory> _list;
        protected ShopProductInfo item = null;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!AuthUtil.CheckAuthorization("PRODUCT_MAN", "EDIT") && !AuthUtil.CheckAuthorization("PRODUCT_MAN", "ADD"))
            {
                ZLCMS.Business.DwzFrame.FrameHelper _fPage = new ZLCMS.Business.DwzFrame.FrameHelper(this);
                _fPage.Alert(new ReturnCode() { statusCode = 300, message = "操作失败-权限不足!" });
                return;

            }
            if (!IsPostBack)
            {
                #region 初始化页面
                fc_open.Config = new Business.UploadFileInfo.UploadConfig()
                       {
                           Thumbnail = new ThumbnailConfig()
                           {
                               Mode = "HW",
                               Auto = true,
                               Name = "thumb",
                               Height = 200,
                               Width = 200
                           },
                           UploadDir = UserKit.GetUserAccountFailLogin() + "/product/"
                       };

                //todo 设置页面控件信息

                int uid = 0;

                Int32.TryParse(Request["uid"], out uid);

                ShopSkuProduct sku = null;
                ShopCategory _categoryDB = null;

                using (NHibernate.ISession session = DotNet.Common.NHibernateUtil.SessionFactoryHelper.CreateSession())
                {
                    if (uid > 0)
                    {
                        item = session.Get<ShopProductInfo>(uid);
                    }
                    ddl_level.DataSource = session.CreateQuery("from MemberLevelDef order by Sort").List<MemberLevelDef>();
                    ddl_level.DataValueField = "LevelId";
                    ddl_level.DataTextField = "Name";
                    ddl_level.DataBind();
                    if (item != null)
                    {
                        //保存uid
                        ViewState["uid"] = uid;
                        sku = session.CreateQuery("from ShopSkuProduct where ProductNo=:no and IsShow='1'")
                            .SetParameter("no", item.ProductNo)
                            .SetMaxResults(1).UniqueResult<ShopSkuProduct>();

                        IList<ShopSearchPropertyProduct> valueList = session.CreateQuery("from ShopSearchPropertyProduct where ProductNo=:pno").SetParameter("pno", item.ProductNo).List<ShopSearchPropertyProduct>();
                        string valueStr = "";
                        for (int i = 0; i < valueList.Count; i++)
                        {
                            if (i == valueList.Count - 1)
                            {
                                valueStr += valueList[i].PropertyItemId;
                            }
                            else
                            {
                                valueStr += valueList[i].PropertyItemId + ",";
                            }
                        }
                        hid_property_item.Value = valueStr;

                        if (item.TypeId != 0)
                        {
                            _categoryDB = session.Get<ShopCategory>(item.TypeId);
                        }
                    }
                    else
                    {
                        item = new ShopProductInfo();
                        _categoryDB = session.CreateCriteria<ShopCategory>().Add(Expression.Eq("Id", int.Parse(Request["cid"]))).UniqueResult<ShopCategory>();

                        ViewState["kind"] = Request["kind"];
                        item.GroundingTime = DateTime.Now;
                        item.EndTime = DateTime.Now.AddYears(1);
                        item.Level = "0";
                    }

                    if (sku == null)
                    {
                        sku = new ShopSkuProduct();
                    }
                    if (_categoryDB != null)
                    {

                        //分类搜索属性
                        IList<ShopSearchPropertyGroup> list = new List<ShopSearchPropertyGroup>();

                        _list = new List<ShopCategory>();

                        GetParentsSearchProperty(_categoryDB.ParentId, session);

                        list = session.CreateCriteria<ShopSearchPropertyGroup>().Add(Expression.Eq("CategoryId", _categoryDB.Id)).AddOrder(NHibernate.Criterion.Order.Asc("Sort")).List<ShopSearchPropertyGroup>();

                        IList<ShopSearchPropertyGroup> currentCategorySPList = session.CreateCriteria<ShopSearchPropertyGroup>().Add(Expression.In("CategoryId", _list.Select(c => c.Id).ToList())).AddOrder(NHibernate.Criterion.Order.Asc("Sort")).List<ShopSearchPropertyGroup>();
                        foreach (ShopSearchPropertyGroup s in currentCategorySPList)
                        {
                            list.Add(s);
                        }
                        rpt_category_property.DataSource = list; //session.CreateCriteria<ShopSearchPropertyGroup>().Add(Expression.Eq("CategoryId", int.Parse(Request["cid"]))).List<ShopSearchPropertyGroup>();
                        rpt_category_property.DataBind();
                    }
                }

                //在此设置控件的初始属性
                tb_name.Text = item.ProductName;

                tb_productno.Text = item.ProductNo;
                tb_no2.Text = item.InteriorCode;
                tb_shortdesc.Text = item.ShortDesc;
                startDate.Text = string.Format("{0:yyyy-MM-dd HH:mm:ss}", item.GroundingTime);
                endDate.Text = string.Format("{0:yyyy-MM-dd HH:mm:ss}", item.EndTime);
                if (!string.IsNullOrEmpty(Request["cid"]))
                    if (_categoryDB != null)
                    {
                        ddl_producttype.SelectedNodeId = _categoryDB.Id;
                        ddl_producttype.SelectedNodeText = _categoryDB.CategoryName;
                    }
                tb_mprice.Text = string.Format("{0}", sku.MarketPrice);
                tb_sprice.Text = string.Format("{0}", sku.SalePrice);
                tb_storage.Text = string.Format("{0}", sku.Storage);
                fc_open.Value = item.ThumbnailImg;
                fc_relatedimgs.Value = item.ProductImg;
                txt_description.Value = item.Description;
                txtParamContent.Value = item.ParamContent;

                ddl_level.SelectedValue = item.Level as string;

                #endregion
            }
            else
            {
                //todo   保存产品
                #region 保存产品

                ICommandResult<EditProductResult> res = new EditProductCommand().Execute(new EditProductParameter()
       {
           PropertyItem = hid_property_item.Value,
           Kind = ViewState["kind"] as string,
           ProductId = ViewState["uid"] == null ? 0 : (int)ViewState["uid"],
           TypeId = ddl_producttype.SelectedNodeId,
           ProductName = tb_name.Text,
           InteriorCode = tb_no2.Text,
           ShortDesc = tb_shortdesc.Text,
           GroundingTime = DateTime.Parse(startDate.Text),
           EndTime = DateTime.Parse(endDate.Text),
           MarketPrice = decimal.Parse(tb_mprice.Text),
           SalePrice = decimal.Parse(tb_sprice.Text),
           Storage = int.Parse(tb_storage.Text),
           Level = ddl_level.SelectedValue,
           ThumbnailImg = fc_open.Value,
           ProductImg = fc_relatedimgs.Value,
           Description = txt_description.Value,
           ParamContent = txtParamContent.Value
       });

                ZLCMS.Business.DwzFrame.FrameHelper _framePage = new ZLCMS.Business.DwzFrame.FrameHelper(this);
                if (res.Error)
                {
                    _framePage.Alert(new ReturnCode() { statusCode = 300, message = "操作失败-参数错误!" });
                }
                else
                {
                    EditProductResult resData = res.Result;
                    _framePage.Alert(new ZLCMS.Business.DwzFrame.ReturnCode()
                    {
                        statusCode = 200,
                        message = "操作成功!",
                        navTabId = _framePage.NavTabId,
                        callbackType = "forward",
                        forwardUrl = "/SystemManage/Basics/Shop/Product/ProductDetail.aspx?tabid=ProductDetail&kind=" + resData.Product.Kind + (Request["submit_op"] != "1" ? ("&uid=" + resData.Product.Id) : "")

                    });
                }
                #endregion
            }
        }

        protected void rpt_category_property_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            //判断里层repeater处于外层repeater的哪个位置（ AlternatingItemTemplate，FooterTemplate，

            //HeaderTemplate，，ItemTemplate，SeparatorTemplate）
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                Repeater rep = e.Item.FindControl("rpt_category_property_item") as Repeater;//找到里层的repeater对象
                ShopSearchPropertyGroup property = (ShopSearchPropertyGroup)e.Item.DataItem;//找到分类Repeater关联的数据项 
                using (var session = SessionFactoryHelper.CreateSession())
                {
                    rep.DataSource = session.CreateQuery("from ShopSearchPropertyItem where SearchPropertyId= :pid").SetParameter("pid", property.Id).List<ShopSearchPropertyItem>();
                    rep.DataBind();
                }
            }
        }


        public void AddPropertyItem(ShopProductInfo productDB, ISession session)
        {
            session.CreateSQLQuery("delete from shop_search_property_product where product_no=:no ").SetParameter("no", productDB.ProductNo).ExecuteUpdate();

            string itemStr = hid_property_item.Value;
            if (!string.IsNullOrEmpty(itemStr))
            {
                string[] itemList = itemStr.Split(',');
                for (int i = 0; i < itemList.Length; i++)
                {
                    session.Save(new ShopSearchPropertyProduct() { ProductNo = productDB.ProductNo, PropertyItemId = Convert.ToInt32(itemList[i]) });
                }
                session.Flush();
            }
        }

        public string IsSelect(int id)
        {
            using (ISession session = DotNet.Common.NHibernateUtil.SessionFactoryHelper.CreateSession())
            {
                int count = Convert.ToInt32(session.CreateQuery("select count(*) from ShopSearchPropertyProduct where PropertyItemId=:id and ProductNo=:pno").SetParameter("pno", item.ProductNo).SetParameter("id", id).UniqueResult());
                if (count != 0)
                {
                    return "checked=checked";
                }
                else
                {
                    return "";
                }
            }
        }

        private void GetParentsSearchProperty(int id, ISession session)
        {
            var parent = session.CreateCriteria<ShopCategory>().Add(Expression.Eq("Id", id)).UniqueResult<ShopCategory>();
            if (parent != null)
            {
                _list.Add(parent);
                GetParentsSearchProperty(parent.ParentId, session);
            }
        }
    }
}